<template>
  <view>
    <text v-if="disabled">{{ customName }}</text>
    <uni-data-select
      v-else
      v-model="props.customId"
      :localdata="customOptions"
      @change="handleChange"
    ></uni-data-select>
  </view>
</template>

<script setup lang="ts">
import {useCustomApi} from "@/api/pm/custom";

defineOptions({ name: 'PmCustomSelect' })

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  customId: {
    type: [String, Number, Array<string | number>],
    default: null,
  },
})

const customName = computed(() => {
  const list = toRaw(allCustomList.value);
  if (!props.customId || !list || !list.length) {
    return '暂无';
  } else {
    const customList = Array.isArray(props.customId) ? props.customId : [props.customId]
    const resUser = list.filter((u: PmCustomForm) => customList.includes(u.id));
    if (resUser) {
      const resUserName = resUser.map(custom => {
        return custom.customerName
      })
      return resUserName.join(',');
    }
    return `未知（${props.customId}）`;
  }
})


type CustomOption = {
  value: string | number,
  text: string,
}
const customOptions = ref<CustomOption[]>([]);

function getUserOptions() {
  const list = toRaw(allCustomList.value);
  if (list && list.length) {
    customOptions.value = list.map((c: PmCustomForm) => {
      return {
        value: c.id,
        text: c.customerName,
      };
    });
  } else {
    customOptions.value = [];
  }
}

const $emit = defineEmits(['update:customId']);
function handleChange(val: string) {
  $emit('update:customId', val);
}

const allCustomList = ref<PmCustomForm[]>([]);
function getAllUserList() {
  useCustomApi().getCompanyAllList().then((res) => {
    if (res.code === 0 && res.data) {
      allCustomList.value = res.data;
      getUserOptions();
    }
  })
}

onLoad(() => {
  getAllUserList();
})
</script>

<style scoped lang="scss">

</style>
